package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionReworkDO;
import com.cssy.xxkj.logic.entity.LogicProductionReworkItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionDispatchingService;
import com.cssy.xxkj.logic.service.ILogicProductionReworkService;
import com.cssy.yd.logic.util.MathUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.OutJsonGrid;
/**
 * 生产返工控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/prorework")
public class ProductionReworkController extends BaseController<LogicProductionReworkDO> {
	
	private static final Logger logger = Logger.getLogger(ProductionReworkController.class);

	private static final String MANAGER = "/xxkj/logic/prorework/ProReworkManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/prorework/ProReworkOperation";// 添加、修改、显示页面

	@Resource(name = "logicProductionReworkService")
	private ILogicProductionReworkService logicProductionReworkService;
	//生产派工Service
	@Resource(name = "logicProductionDispatchingService")
	private ILogicProductionDispatchingService logicProductionDispatchingService;

	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setOrderBy("bizCreatorDate desc");
		SearchResult result = logicProductionReworkService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicProductionReworkDO rework = logicProductionReworkService.findListById(id);
			model.addAttribute("rework", rework);
		}
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionReworkDO prodispat = logicProductionReworkService.findListById(id);
			List<LogicProductionReworkItemDO> soitem = logicProductionReworkService.findDispatItemList(prodispat.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionReworkDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionReworkService.dispatSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionReworkDO ld = logicProductionReworkService.findListById(field);
				logicProductionReworkService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping("/gridBomitems")
	public void gridBomitems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionDispatchingDO proDispatch = logicProductionDispatchingService.findListById(id);
			List<LogicProductionDispatchingItemDO> proDispatchItem = logicProductionDispatchingService.findDispatItemList(proDispatch.getId());
			if(proDispatchItem!=null&&!proDispatchItem.isEmpty()&&proDispatchItem.size()>0){
				List<LogicProductionReworkItemDO> dailylist = this.dispatchingToDaily(proDispatchItem,proDispatch.getZd001FormCode());
				OutJsonGrid out = new OutJsonGrid(dailylist);
				out.printJSon(response);
			}
		}
	}
	
	private List<LogicProductionReworkItemDO> dispatchingToDaily(List<LogicProductionDispatchingItemDO> dispatching,String code) throws Exception{
		List<LogicProductionReworkItemDO> dailylist = new ArrayList<LogicProductionReworkItemDO>();
		List<LogicProductionReworkItemDO> dilylist = this.listItem(code);
		for(int i=0;i<dispatching.size();i++){
			LogicProductionReworkItemDO daily= new LogicProductionReworkItemDO();
			daily.setZd001ProReworkId(dispatching.get(i).getZd001ProDispatId());
			daily.setZd029Process(dispatching.get(i).getZd029Process());
			daily.setZd028WorkShop(dispatching.get(i).getZd028WorkShop());
			daily.setZd002ProReworkCode(dispatching.get(i).getZd002ProDispatCode());
			daily.setZd003CustomerId(dispatching.get(i).getZd003CustomerId());
			daily.setZd004CustomerCode(dispatching.get(i).getZd004CustomerCode());
			daily.setZd005CustomerName(dispatching.get(i).getZd005CustomerName());
			daily.setZd006MaterialsCode(dispatching.get(i).getZd006MaterialsCode());
			daily.setZd006MaterialsName(dispatching.get(i).getZd006MaterialsName());
			daily.setZd006MaterialsId(dispatching.get(i).getZd006MaterialsId());
			daily.setZd007UseCode(dispatching.get(i).getZd007UseCode());
			daily.setZd008UseName(dispatching.get(i).getZd008UseName());
			daily.setZd009MaterialsBatch(dispatching.get(i).getZd009MaterialsBatch());
			daily.setZd010MaterialsModel(dispatching.get(i).getZd010MaterialsModel());
			daily.setZd011MaterialsSpec(dispatching.get(i).getZd011MaterialsSpec());
			daily.setZd012MaterialsUnit(dispatching.get(i).getZd012MaterialsUnit());
			daily.setZd014Price(dispatching.get(i).getZd013Price());
			daily.setZd015DeliveryDate(dispatching.get(i).getZd014DeliveryDate());
			daily.setZd017StorageQuantity(dispatching.get(i).getZd017StorageQuantity());
			daily.setZd018OutboundQuantity(dispatching.get(i).getZd018OutboundQuantity());
			daily.setZd019ReturnQuantity(dispatching.get(i).getZd019ReturnQuantity());
			daily.setZd020Remark(dispatching.get(i).getZd020Remark());
			daily.setZd021MaterialsDescription(dispatching.get(i).getZd021MaterialsDescription());
			daily.setZd022OpenBatch(dispatching.get(i).getZd022OpenBatch());
			daily.setZd023MaterialsSize(dispatching.get(i).getZd023MaterialsSize());
			daily.setZd024MaterialsPicture(dispatching.get(i).getZd024MaterialsPicture());
			daily.setZd025MaterialsAnnex(dispatching.get(i).getZd025MaterialsAnnex());
			daily.setZd026MaterialsColor(dispatching.get(i).getZd026MaterialsColor());
			daily.setZd027MaterialsQuality(dispatching.get(i).getZd027MaterialsQuality());
			//daily.setZd030PlanQuantity(dispatching.get(i).getZd013Quantity());
			daily.setZd016ProductionQuantity(this.getProductionQuantity(dilylist, daily.getZd029Process()));
			/*if(daily.getZd016ProductionQuantity().compareTo(new BigDecimal(0.0))==1){
				BigDecimal bg =MathUtil.mathUtil.subtract(dispatching.get(i).getZd013Quantity(), daily.getZd016ProductionQuantity());
				daily.setZd013Quantity(bg);
			 }else{
				 daily.setZd013Quantity(dispatching.get(i).getZd013Quantity());
			}*/
			if(daily.getZd013Quantity().compareTo(new BigDecimal(0.0))==1){
				dailylist.add(daily);
		    }
		}
		return dailylist;
	}
	
	/**
	 * 查询当前生产派工单已返工的物料
	 */
	private List<LogicProductionReworkItemDO> listItem(String plan)
			throws Exception {
		List<LogicProductionReworkItemDO> list = new ArrayList<LogicProductionReworkItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		scs.addCondition("zd002OriCode", plan, SearchCondition.OP_EQUAL);
		List<LogicProductionReworkDO> result = logicProductionReworkService.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionReworkItemDO> dispatItem = logicProductionReworkService.findDispatItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}
	
	private BigDecimal getProductionQuantity(List<LogicProductionReworkItemDO> list,String proess){
		BigDecimal big = new BigDecimal(0.0);
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(list.get(i).getZd029Process().equals(proess)){
					big=MathUtil.mathUtil.addtract(big, list.get(i).getZd013Quantity());
				}
			}
		}
		return big;
	}
}
